package com.marklogic.ps.servicetester.services;

import java.util.Collection;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import com.marklogic.ps.servicetester.domain.ServerConnectionInfo;
import com.marklogic.ps.servicetester.domain.ServiceTesterPreferences;

public class PreferencesServiceImpl {
	
	public ServiceTesterPreferences loadPreferences() {
		ServiceTesterPreferences prefs = null;
		Preferences myPreferences = Preferences.userNodeForPackage(this.getClass());
		int serverCount = myPreferences.getInt("serverCount", 0);
		//List<ServerConnectionInfo> servers = null;
		if (serverCount > 0) {
			prefs = new ServiceTesterPreferences();
			for (int i = 1; i <= serverCount; i++) {
				String uri = myPreferences.get("server."+i+"uri", "");
				String user = myPreferences.get("server."+i+"username", "");
				String pass = myPreferences.get("server."+i+"password", "");
				ServerConnectionInfo sci = new ServerConnectionInfo(uri, user, pass);
				sci.setId(i);
				//servers.add(sci);
				prefs.addServerConnectionInfo(sci);
			}
		} else {
			prefs = getDefaultPrefs();
			savePreferences(prefs);
		}
		return prefs;
	}
	
	private ServiceTesterPreferences getDefaultPrefs() {
		ServiceTesterPreferences prefs = new ServiceTesterPreferences();
		return prefs;
	}
	
	public void savePreferences(ServiceTesterPreferences prefs) {
		Preferences myPreferences = Preferences.userNodeForPackage(this.getClass());
		try {
			myPreferences.clear();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
		Collection <ServerConnectionInfo> sciMap = prefs.getServerConnectionInfo();
		int serverCount = sciMap.size();
		myPreferences.putInt("serverCount", serverCount);
		if (serverCount > 0) {
			int i = 1;
			for (ServerConnectionInfo sci : sciMap) {
				myPreferences.put("server."+i+"uri", sci.getBaseUrl());
				myPreferences.put("server."+i+"username", sci.getUsername());
				myPreferences.put("server."+i+"password", sci.getPassword());
				i++;
			}
		}
		try {
			myPreferences.flush();
		} catch (BackingStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
